package com.hdu.other.dp.intervalDp;

public class lc312 {
    class Solution {
        public int maxCoins(int[] nums) {
            int n = nums.length;
            int[] arr = new int[n + 2];
            arr[0] = 1;
            for (int i = 1; i <= n; i++) {
                arr[i] = nums[i - 1];
            }
            arr[n + 1] = 1;
            int[][] dp = new int[n + 2][n + 2];
            for (int i = 0; i < n + 2; i++) {
                for (int j = 0; j < n + 2; j++) {
                    dp[i][j] = -1;
                }
            }
            return f(arr, dp, 1, n);
        }

        int f(int[] arr, int[][] dp, int l, int r) {
            if (l == r) {
                return arr[l - 1] * arr[l] * arr[r + 1];
            } else if (dp[l][r] != -1) {
                return dp[l][r];
            } else {
                // l or r 处的气球最后爆
                int ans = Math.max(
                        f(arr, dp, l, r - 1) + arr[l - 1] * arr[r] * arr[r + 1],
                        f(arr, dp, l + 1, r) + arr[l - 1] * arr[l] * arr[r + 1]
                );
                // 枚举 l + 1 , r - 1 上面的气球最后爆
                for (int k = l + 1; k < r; k++) {
                    ans = Math.max(
                            ans,
                            f(arr, dp, l, k - 1) + f(arr, dp, k + 1, r) + arr[l - 1] * arr[k] * arr[r + 1]
                    );
                }
                return dp[l][r] = ans;
            }
        }
    }
}
